<?php

namespace app\controller;
use app\BaseController;
use think\facade\Db;
use think\facade\Request;
use think\response\Json;
use app\model\VerificationCodeModel;

class VerificationCode extends BaseController
{
    /**
     * 验证码列表
     * @return Json
     */
    public function list(): Json
    {
        // 分页参数（优先取limit，其次pageSize）
        $page = max(Request::param('page/d', 1), 1);
        $limit = max(Request::param('limit/d', Request::param('pageSize/d', 10)), 1);

        // 搜索参数
        $id = Request::param('id', '');
        $verificationCodeId = Request::param('verification_code_id', '');
        $code = Request::param('code', '');
        $phone = Request::param('phone', '');
        $type = Request::param('type/d', 0); // 0表示全部类型
        $isVerified = Request::param('is_verified/d', -1); // 默认-1表示全部

        $query = VerificationCodeModel::query();

        // ID搜索
        if ($id !== '' && is_numeric($id)) {
            $query->where('id', (int)$id);
        }
        // 验证码ID搜索
        if ($verificationCodeId !== '') {
            $query->where('verification_code_id', $verificationCodeId);
        }
        // 其他条件
        if ($code !== '') {
            $query->where('code', $code);
        }
        if ($phone !== '') {
            $query->where('phone', $phone);
        }
        // 处理类型条件
        if ($type != 0) {
            $query->where('type', $type);
        }
        // 处理验证状态条件
        if ($isVerified !== -1) { // 仅当参数存在且不为-1时筛选
            $query->where('is_verified', $isVerified);
        }

        $paginator = $query->field([
            'id', 'verification_code_id', 'type', 'phone', 'code',
            'is_verified', 'sent_time', 'created_time'
        ])->paginate([
            'page'      => $page,
            'list_rows' => $limit,
            'var_page'  => 'page'
        ]);

        return json([
            'code' => 0,
            'msg'  => '成功',
            'data' => [
                'list' => $paginator->items(),
                'pagination' => [
                    'total'    => $paginator->total(),
                    'page'     => $paginator->currentPage(),
                    'limit'    => $paginator->listRows(),
                    'pages'    => $paginator->lastPage(),
                    'has_more' => $paginator->currentPage() < $paginator->lastPage()
                ]
            ]
        ]);
    }

    /**
     * 导出验证码数据
     */
    public function export()
    {
        // 搜索参数（与列表保持一致）
        $id = Request::param('id', '');
        $verificationCodeId = Request::param('verification_code_id', '');
        $code = Request::param('code', '');
        $phone = Request::param('phone', '');
        $type = Request::param('type/d', 0);
        $isVerified = Request::param('is_verified/d', -1); // 默认-1表示全部

        $query = VerificationCodeModel::query();

        // 条件处理（与列表逻辑一致）
        if ($id !== '' && is_numeric($id)) {
            $query->where('id', (int)$id);
        }
        if ($verificationCodeId !== '') {
            $query->where('verification_code_id', $verificationCodeId);
        }
        if ($code !== '') {
            $query->where('code', $code);
        }
        if ($phone !== '') {
            $query->where('phone', $phone);
        }
        if ($type != 0) {
            $query->where('type', $type);
        }
        // 处理验证状态条件
        if ($isVerified !== -1) { // 仅当参数存在且不为-1时筛选
            $query->where('is_verified', $isVerified);
        }

        $list = $query->field('id, verification_code_id, type, phone, code, is_verified, sent_time, created_time')
            ->select()
            ->toArray();

        // 数据格式化
        foreach ($list as &$item) {
            $item['type_text'] = match ($item['type']) {
                1 => '登录',
                2 => '修改密码',
                3 => '注销账号',
                default => '未知'
            };
            $item['is_verified_status'] = $item['is_verified'] == 1 ? '已验证' : '未验证';
            $item['sent_time'] = strtotime($item['sent_time']);
            $item['created_time'] = strtotime($item['created_time']);
        }

        $filename = 'verification_codes_' . date('YmdHis') . '.csv';
        header('Content-Type: text/csv');
        header('Content-Disposition: attachment; filename="' . $filename . '"');
        $output = fopen('php://output', 'w');
        
        // 表头
        fputcsv($output, [
            '记录ID', 
            '验证码ID', 
            '类型', 
            '手机号', 
            '验证码', 
            '验证状态', 
            '发送时间', 
            '创建时间'
        ]);
        
        foreach ($list as $row) {
            fputcsv($output, [
                $row['id'],
                $row['verification_code_id'],
                $row['type_text'],
                $row['phone'],
                $row['code'],
                $row['is_verified_status'],
                date('Y-m-d H:i:s', $row['sent_time']),
                date('Y-m-d H:i:s', $row['created_time'])
            ]);
        }
        fclose($output);
    }
}    